package com.birtboot.core;

import com.birtboot.http.HttpServletRequest;

import java.io.*;
import java.net.Socket;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class ClientHandler implements Runnable {
    private Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        try {
           //1.解析请求
            HttpServletRequest request=new HttpServletRequest(socket);
            String path=request.getUri();
            System.out.println("抽象路径："+path);
            //2处理请求

            //3发送响应
            //定位类加载路径固定写法
            File baseDir=new File(
                    ClientHandler.class.getClassLoader().getResource(".").toURI()
            );
            File staticDir=new File(baseDir,"static");
            File file=new File(staticDir,path);

            OutputStream out=socket.getOutputStream();
            //3.1发送状态行
            String line= "HTTP/1.1 200 OK";
            out.write(line.getBytes(StandardCharsets.ISO_8859_1));
            out.write(13);
            out.write(10);
            //发送响应头
            line= "Content-Type: text/html";
            out.write(line.getBytes(StandardCharsets.ISO_8859_1));
            out.write(13);
            out.write(10);

            line= "Content-Length: "+file.length();
            out.write(line.getBytes(StandardCharsets.ISO_8859_1));
            out.write(13);
            out.write(10);

            out.write(13);
            out.write(10);
            //3.3发送响应正文（index.html页面内容发送出去）
            FileInputStream fis=new FileInputStream(file);
            byte[] data=new byte[1024*10];
            int len;
            while ((len=fis.read(data))!=-1){
                out.write(data,0,len);
            }
        } catch (IOException | URISyntaxException e) {
            e.printStackTrace();
        } finally {
            //遵循HTTP协议要求,一问一答后与客户端断开连接
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


}
